package com.yonyou.pmclouds.completedcollate.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.iuap.print.client.utils.JsonUtil;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.StorageFactory;
import com.yonyou.pmclouds.basecom.view.DisableWrap;
import com.yonyou.pmclouds.businessobject.util.BusinessObjectConsts;
import com.yonyou.pmclouds.businessobject.util.PrintPreviewObj2Html;
import com.yonyou.pmclouds.completedcollate.entity.NamePkVO;
import com.yonyou.pmclouds.completedcollate.rmiitf.CompletedCollateQuery;
import com.yonyou.pmclouds.constructionlog.entity.ConstructionLogVO;
import com.yonyou.pmclouds.constructionlog.rmiitf.ConstructionLogQuery;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseInfo;
import com.yonyou.pmclouds.inspectitem.entity.InspectItemBillStatusConst;
import com.yonyou.pmclouds.inspectitem.entity.InspectItemVO;
import com.yonyou.pmclouds.inspectitem.rmiitf.InspectItemService;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.processinspect.entity.ProcedureInspectBodyVO;
import com.yonyou.pmclouds.processinspect.entity.ProcedureInspectVO;
import com.yonyou.pmclouds.processinspect.rmiitf.ProcedureInspectRemoteService;
import com.yonyou.pmclouds.team.entity.TeamMemberVO;
import com.yonyou.pmclouds.team.rmiitf.TeamEnterpriseQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 竣工资料预览业务数据接口
 *
 * @author yzx
 * @Date: 2018/5/29 15:54
 */
@RestController
@RequestMapping("/completedCollate/preview")
public class CompletedCollatePreviewController {
    @Value("${print.perLineNum}")
    private int perLineNum;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ConstructionLogQuery constructionLogQuery;

    @Autowired
    private UserInfoQuery userQuery;
    @Autowired
    private StorageFactory storageFactory;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProcedureInspectRemoteService procedureInspectService;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private CompletedCollateQuery collateQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private InspectItemService inspectItemService;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamEnterpriseQuery enterpriseQuery;
    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;

    private static final String[] USER_ID_FIELDS = {ConstructionLogVO.CREATOR};
    private static final String[] USER_NAME_FIELDS = {ConstructionLogVO.CREATOR_NAME};

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 施工记录打印预览数据获取接口
     *
     * @param request
     * @return java.util.Map<java.lang.String   ,   java.lang.Object>
     * @author yzx
     * @date 2018/5/31 13:58
     */
    @DisableWrap
    @RequestMapping("/printPreviewConstructionLog")
    public Map<String, Object> printPreviewConstructionLog(HttpServletRequest request) throws BusinessException {
        String pkBill = (String) JsonUtil.jsonToMap(request.getParameter("params")).get("pkBill");
        Map<String, Object> result = new HashMap<>();
        ConstructionLogVO constructionLog = constructionLogQuery.queryOne(pkBill);
        constructionLog.setStrCreationtime(sdf.format(constructionLog.getCreationtime()));
        // 通过项目，制单人确定施工单位
        constructionLog.setConstructionunit_name(getEnterpriseNameByProjectIdAndUserId(constructionLog.getPk_project(), constructionLog.getCreator()));
        // 获取合格率
        Map<String, BigDecimal> doubleMap = inspectItemService.queryPassRateOfConstructLog(new String[]{constructionLog.getPk_constructionlog()});
        if (doubleMap.get(constructionLog.getPk_constructionlog()) != null) {
            constructionLog.setQualification_rate(doubleMap.get(constructionLog.getPk_constructionlog()) + "%");
        }
        // 为创建人，日期赋值
        userQuery.tranUserInfoField(new ConstructionLogVO[]{constructionLog}, USER_ID_FIELDS, USER_NAME_FIELDS);
        constructionLog.setStrCreationtime(sdf.format(constructionLog.getCreationtime()));
        result.put(BusinessObjectConsts.PM_CONSTRUCTIONLOG, new ConstructionLogVO[]{constructionLog});
        // 处理照片地址
        InspectItemVO[] inspectitems = constructionLog.getInspectitems();
        String[] inspectItemPks = new String[inspectitems.length];
        for (int i = 0; i < inspectitems.length; i++) {
            inspectItemPks[i] = inspectitems[i].getPk_inspectitem();
        }
        InspectItemVO[] inspectItemVOS = inspectItemService.queryInspectItemsInfoByPks(inspectItemPks);
        for (int i = 0; i < inspectItemVOS.length; i++) {
            // 将检查项更换成数据明细的检查项
            inspectItemVOS[i].setPk_constructionlog(inspectitems[i].getPk_bill());
        }
        PrintPreviewObj2Html obj2Html = new PrintPreviewObj2Html(PrintPreviewObj2Html.BASE_PREFIX, PrintPreviewObj2Html.IMG, perLineNum);
        if (inspectitems != null) {
            for (InspectItemVO inspectItemVO : inspectItemVOS) {
                if (inspectItemVO.getPictures() != null) {
                    String picHtml = obj2Html.urls2Html(storageFactory.getStorageUtil().signUrlForMultiPictures(inspectItemVO.getPictures(), null, request));
                    inspectItemVO.setPicture_address(picHtml);
                }
                // 为数据显示处理成字符串
                if (inspectItemVO.getDatas() != null && inspectItemVO.getDatas().length > 0) {
                    StringBuilder strDatas = new StringBuilder();
                    for (double data : inspectItemVO.getDatas()) {
                        strDatas.append(data).append(";");
                    }
                    inspectItemVO.setItemDatas(strDatas.toString());
                }
                // 质量状态
                switch (inspectItemVO.getBillstatus()) {
                    case InspectItemBillStatusConst.BILLSTATUS_PASS:
                        inspectItemVO.setItemQuality(InspectItemBillStatusConst.BILLSTATUS_PASS_MSG);
                        break;
                    case InspectItemBillStatusConst.BILLSTATUS_NO_PASS:
                        inspectItemVO.setItemQuality(InspectItemBillStatusConst.BILLSTATUS_NO_PASS_MSG);
                        break;
                    case InspectItemBillStatusConst.BILLSTATUS_NOT_FIT:
                        inspectItemVO.setItemQuality(InspectItemBillStatusConst.BILLSTATUS_NOT_FIT_MSG);
                        break;
                    default:
                        break;
                }
            }
        }

        constructionLog.setInspectitems(inspectItemVOS);
        result.put(BusinessObjectConsts.SUB_PM_INSPECTITEM, constructionLog.getInspectitems());
        return result;
    }

    /**
     * 通过项目，和制单人pk，获取企业名称
     *
     * @param pkProject, pkUser
     * @return java.lang.String
     * @author yzx
     * @date 2018/6/11 15:30
     */
    private String getEnterpriseNameByProjectIdAndUserId(String pkProject, String pkUser) throws BusinessException {
        String enterpriseName = "";
        TeamMemberVO[] teamMemberVOS = collateQuery.getMemberByProject(pkProject);
        if(teamMemberVOS != null && teamMemberVOS.length > 0) {
            for(TeamMemberVO memberVO : teamMemberVOS) {
                if(memberVO.getPkUser().equalsIgnoreCase(pkUser)) {
                    String enterpriseId = memberVO.getPkEnterprise();
                    EnterpriseInfo enterpriseInfo= enterpriseInfoQuery.queryEnterpriseById(enterpriseId);
                    if(enterpriseInfo != null) {
                        enterpriseName = enterpriseInfo.getName();
                        break;
                    }
                }
            }
        }
        return enterpriseName;
    }

    /**
     * 工序报验打印预览数据获取接口
     *
     * @param request
     * @return java.util.Map<java.lang.String                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                               java.lang.Object>
     * @author yzx
     * @date 2018/5/31 16:14
     */
    @DisableWrap
    @RequestMapping("/printPreviewProcedureInspect")
    public Map<String, Object> printPreviewProcedureInspect(HttpServletRequest request) throws BusinessException {
        String pkBill = (String) JsonUtil.jsonToMap(request.getParameter("params")).get("pkBill");
        Map<String, Object> result = new HashMap<>();
        ProcedureInspectVO procedureInspectVO = getProcedureInspectVO(pkBill);
        // 为施工单位，监理单位赋值
        procedureInspectVO.setConstructionunit_name(getEnterpriseNameByProjectIdAndUserId(procedureInspectVO.getPk_project(), procedureInspectVO.getCreator()));
        procedureInspectVO.setSupervisionunit_name(getEnterpriseNameByProjectIdAndUserId(procedureInspectVO.getPk_project(), procedureInspectVO.getAcceptor()));
        procedureInspectVO.setStrCreationtime(sdf.format(procedureInspectVO.getCreationtime()));
        result.put(BusinessObjectConsts.PMBD_PROCEDUREINSPECT, procedureInspectVO);
        // 通过工序报验表体中关联的施工记录主键填充施工记录内容
        if (procedureInspectVO.getBodyVOs() != null) {
            Set<String> constructionLogPks = new HashSet<>();
            for (ProcedureInspectBodyVO bodyVO : procedureInspectVO.getBodyVOs()) {
                constructionLogPks.add(bodyVO.getPk_construct_record());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("ids", constructionLogPks);
            List<ConstructionLogVO> constructionLogVOS = constructionLogQuery.queryVosByParams(params);
            for (ConstructionLogVO constructionLogVO : constructionLogVOS) {
                constructionLogVO.setStrCreationtime((sdf.format(constructionLogVO.getCreationtime())));
                constructionLogVO.setPk_process_inspect(procedureInspectVO.getPk_process_inspect());
            }
            // 为创建人赋值
            userQuery.tranUserInfoField(constructionLogVOS.toArray(new ConstructionLogVO[constructionLogVOS.size()]), USER_ID_FIELDS, USER_NAME_FIELDS);
            result.put(BusinessObjectConsts.SUB_PM_CONSTRUCTIONLOG, constructionLogVOS);
        }
        return result;
    }

    private ProcedureInspectVO getProcedureInspectVO(String pkBill) throws BusinessException {
        ProcedureInspectVO procedureInspectVO = procedureInspectService.queryPrcInspectDetail(pkBill);

        userQuery.tranUserInfoField(new ProcedureInspectVO[]{procedureInspectVO},
                new String[]{ProcedureInspectVO.CREATOR, ProcedureInspectVO.ACCEPTOR},
                new String[]{ProcedureInspectVO.CREATORNAME, ProcedureInspectVO.ACCEPTORNAME});
        userQuery.tranUserInfoField(procedureInspectVO.getBodyVOs(),
                new String[]{ProcedureInspectBodyVO.RECORD_CREATOR},
                new String[]{ProcedureInspectBodyVO.RECORD_CREATOR_NAME});
        return procedureInspectVO;
    }

    @PostMapping("/getQuoteNameAndPk")
    public List<NamePkVO> getQuoteNameAndPk(@RequestBody String[] procedureinspectpks) throws BusinessException {
        if (procedureinspectpks == null || procedureinspectpks.length == 0) {
            return new ArrayList<>();
        }
        return collateQuery.getQuoteNameAndPk(procedureinspectpks);
    }
}
